<template>
  <div class="upload-image-container">
    <el-upload
      :http-request="customRequest"
      :show-file-list="false"
      :accept="fileType.join(',')"
      :disabled="disabled"
      :before-upload="beforeUpload"
      :on-success="handleSuccess"
    >
      <div v-if="modelValue" class="image-preview">
        <img :src="modelValue" alt="预览图片" />
        <div v-if="!disabled" class="image-actions">
          <el-button size="small" @click.stop="handleEdit">编辑</el-button>
          <el-button v-if="showDelete" size="small" type="danger" @click.stop="handleDelete">删除</el-button>
        </div>
      </div>
      <div v-else class="upload-placeholder">
        <el-icon><Plus /></el-icon>
        <span>点击上传</span>
      </div>
    </el-upload>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import request from '@/config/axios'

const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  disabled: {
    type: Boolean,
    default: false
  },
  fileSize: {
    type: Number,
    default: 5
  },
  fileType: {
    type: Array,
    default: () => ['image/jpeg', 'image/png', 'image/gif']
  },
  showDelete: {
    type: Boolean,
    default: true
  }
})

const emit = defineEmits(['update:modelValue'])
const uploadInput = ref(null)

const handleEdit = () => {
  const input = document.querySelector('.el-upload__input')
  if (input) {
    input.click()
  }
}

const handleDelete = () => {
  emit('update:modelValue', '')
}

const beforeUpload = (rawFile) => {
  // 检查文件大小
  const isLtSize = rawFile.size / 1024 / 1024 < props.fileSize
  if (!isLtSize) {
    ElMessage.warning(`上传图片大小不能超过 ${props.fileSize}MB!`)
    return false
  }
  
  // 检查文件类型
  const isTypeValid = props.fileType.includes(rawFile.type)
  if (!isTypeValid) {
    ElMessage.warning('上传图片格式不正确!')
    return false
  }
  
  return true
}

const customRequest = ({ file, onSuccess, onError }) => {
  const formData = new FormData()
  formData.append('file', file)
  
  request.post('/file/upload', formData)
    .then(res => {
      // 假设后端返回的图片地址在 res.data 中
      const imageUrl = res.data || res
      emit('update:modelValue', imageUrl)
      onSuccess(res)
      ElMessage.success('上传成功')
    })
    .catch(err => {
      onError(err)
      ElMessage.error('上传失败')
    })
}
</script>

<style scoped>
.upload-image-container {
  width: 150px;
  height: 150px;
  position: relative;
  display: inline-block;
  vertical-align: middle;
}

.image-preview {
  width: 150px;
  height: 150px;
  position: relative;
  border: 1px dashed #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
}

.image-preview img {
  max-width: 100%;
  max-height: 100%;
  object-fit: cover;
  display: block;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  margin: auto;
}

.image-actions {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.5);
  padding: 5px;
  display: flex;
  justify-content: space-around;
}

.upload-placeholder {
  width: 150px;
  height: 150px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border: 1px dashed #dcdfe6;
  border-radius: 4px;
  cursor: pointer;
}

.upload-placeholder:hover {
  border-color: #409eff;
  color: #409eff;
}

.upload-placeholder .el-icon {
  font-size: 24px;
  margin-bottom: 10px;
}
</style>
